package com.web44.spring.service.impl;

import com.web44.spring.mapper.IBookMapper;
import com.web44.spring.mapper.IUserMapper;
import com.web44.spring.mapper.impl.BookMapper;
import com.web44.spring.mapper.impl.UserMapper;
import com.web44.spring.service.IUserBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Title: UserBookService
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2024/1/10 14:56
 */
@Service
public class UserBookService implements IUserBookService {

    @Autowired
    private IUserMapper userMapper;
    @Autowired
    private IBookMapper bookMapper;

    /**
     * readOnly=true 控制只读事务 只能操作检索操作 不能存在增删改操作
     * @param userId
     * @param bookId
     */
    // @Transactional(readOnly=true) 只读事务
    // @Transactional(timeout = -1) 延迟事务 多长时间之内必须完成 如果超时就回滚
    // @Transactional(noRollbackFor=ArithmeticException.class) 指定异常的事务 不回滚
   // @Transactional(propagation= Propagation.REQUIRED)  // 多次操作在同一个事务中

    @Override
    // @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void buy(int userId, int bookId)  {
//        try {
//            Thread.sleep(3500);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
        // 1 检索图书价格
        double price= bookMapper.queryBookPriceById(bookId);
        // 2 修改图书库存
        bookMapper.updateBookStoreById(bookId);
        // 3 修改用户余额
        userMapper.updateBalance(userId,price);
//        System.out.println(1/0);
    }
}
